package dletc.thread;

/**
 * 模拟龟兔赛跑
 */
public class Race implements Runnable {

    private String winner; //获胜者

    @Override
    public void run() {

        //先跑到100步就是赢家 winner
        for (int i = 1; i <= 100; i++) {

            //模拟让兔子睡觉
            if (Thread.currentThread().getName().equals("兔子") && i % 10 == 0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //判断比赛是否结束
            boolean gameOver = gameOver(i);
            if (gameOver) {
                break;
            }
            //打印线程步数
            System.out.println(Thread.currentThread().getName() + "--》跑了第" + i + "步");
        }
    }

    //判断赛程结束
    private boolean gameOver(int step) {
        if (winner != null) {
            return true; //已经有胜利者了
        }
        {
            //还没有胜利者,当步数大于等于100 比赛结束 赋值冠军
            if (step >= 100) {
                winner = Thread.currentThread().getName();
                System.out.println("winner is " + winner);
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Race race = new Race();
        Thread thread1 = new Thread(race, "兔子");
        Thread thread2 = new Thread(race, "乌龟");
        thread1.start();
        thread2.start();
    }
}
